<script setup>
import { ref } from 'vue'
import api from '@/api'
import collections from './collections.vue'
import { parsePage, parseQuery } from '@/utils'
import { useRoute, useRouter } from 'vue-router'
import { Modal } from '@arco-design/web-vue'
import { transformDuration } from '@/utils'

const $route = useRoute()
const $router = useRouter()

const department = ref(null)
const departments = ref([])
const departmentsLoading = ref(false)
const getDepartments = async () => {
  departmentsLoading.value = true
  try {
    departments.value = await api.get('departments/options')
    if (departments.value.length > 0) {
      changeDepartment(departments.value[0])
    }
  } catch (error) {
    console.error(error)
  }
  departmentsLoading.value = false
}

const changeDepartment = (item) => {
  department.value = item
  getListData()
  getCollections()
}

// 加载课程
const courses = ref([])
const getCourses = async () => {
  courses.value = await api.get('courses/options')
}
getCourses()

const listFormData = ref({
  page: parsePage($route.query.page, 1),
  collection_id: '',
})
const listData = ref([])
const listTotal = ref(0)
const listLoading = ref(false)
const getListData = async (page = 1) => {
  listLoading.value = true
  try {
    listFormData.value.page = page
    const query = parseQuery(listFormData.value)
    $router.replace({ query })
    const res = await api.get(`departments/${department.value.id}/courses`, {
      params: query,
    })
    listData.value = res.data
    listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}
const resetListData = () => {
  listFormData.value.keyword = ''
  listFormData.value.collection_id = ''
  getListData()
}

const collectionsOptions = ref([])
const collectionsOptionsLoading = ref(false)
const getCollections = async () => {
  collectionsOptionsLoading.value = true
  try {
    collectionsOptions.value = await api.get(
      `departments/${department.value.id}/collections`
    )
  } catch (error) {
    console.error(error)
  }
  collectionsOptionsLoading.value = false
}

const formRef = ref()
const formVisible = ref(false)
const formLoading = ref(false)
const formItem = ref(null)
const formData = ref({
  course_ids: [],
  department_id: '',
  collection_id: '',
})
const formRules = {
  course_ids: [
    {
      required: true,
      message: '请选择课程',
    },
  ],
  collection_id: [
    {
      required: true,
      message: '请选择板块',
    },
  ],
}
const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }

  formLoading.value = true

  try {
    if (formItem.value) {
      await api.put('courses/' + formItem.value.id, formData.value)
    } else {
      await api.post(
        `departments/${department.value.id}/courses`,
        formData.value
      )
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }

  formLoading.value = false

  return false
}

const create = () => {
  formRef.value?.resetFields()
  formItem.value = null
  formVisible.value = true
}

const del = (item) => {
  Modal.confirm({
    title: '删除员工',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete(`departments/${department.value.id}/courses/${item.id}`)

      getListData()
    },
  })
}

const collectionsRef = ref()

getDepartments()
</script>

<template>
  <div class="page">
    <div class="aside">
      <div>
        <a-empty v-if="!departments.length" class="empty" />
        <div
          class="item"
          :class="{ active: department.id == item.id }"
          @click="changeDepartment(item)"
          v-for="(item, index) in departments"
        >
          {{ item.name }}
        </div>
      </div>
    </div>

    <div class="body">
      <div class="header">
        <a-space>
          <a-button type="primary" @click="create">添加课程</a-button>
        </a-space>

        <a-form
          :model="listFormData"
          class="page-form"
          layout="inline"
          @submit="getListData()"
        >
          <a-space>
            <a-select
              placeholder="所属板块"
              v-model="listFormData.collection_id"
              allow-clear
              allow-search
            >
              <a-option v-for="item in collectionsOptions" :value="item.id">
                <div class="option-collection">
                  <div class="img">
                    <img :src="item.image" />
                  </div>
                  <div class="content">{{ item.name }}</div>
                </div>
              </a-option>
            </a-select>

            <a-input
              v-model.trim="listFormData.keyword"
              placeholder="课程名称"
              allow-clear
            />

            <a-button type="primary" html-type="submit">
              <template #icon><icon-search /></template>
              查询
            </a-button>

            <a-button @click="resetListData">
              <template #icon><icon-refresh /></template>重置
            </a-button>
          </a-space>
        </a-form>
      </div>

      <a-table
        :loading="listLoading"
        @page-change="getListData"
        class="table"
        style="border-bottom: 1px solid #e5e6eb"
        :data="listData"
        :pagination="{
          simple: true,
          showTotal: true,
          size: 'small',
          total: listTotal,
          pageSize: 15,
          current: listFormData.page,
        }"
      >
        <template #columns>
          <a-table-column title="序号" :width="60">
            <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          </a-table-column>
          <a-table-column title="板块">
            <template #cell="{ record }">
              <div class="cell-collection" v-if="record.collection">
                <div class="img"><img :src="record.collection.image" /></div>
                <div>{{ record.collection.name }}</div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="课程">
            <template #cell="{ record }">
              <div class="cell-course">
                <div class="img"><img :src="record.course.image" /></div>
                <div class="content">
                  <div class="title">{{ record.course.name }}</div>
                  <div class="description">{{ record.course.description }}</div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="课程总时长">
            <template #cell="{ record }">
              {{ transformDuration(record.course.duration) }}
            </template>
          </a-table-column>
          <a-table-column title="章节数">
            <template #cell="{ record }">{{ record.course.count }}</template>
          </a-table-column>
          <a-table-column title="观看人数">
            <template #cell="{ record }">
              {{ record.watch_count }}
            </template>
          </a-table-column>
          <a-table-column title="观看总时长">
            <template #cell="{ record }">
              {{ transformDuration(record.watch_duration) }}
            </template>
          </a-table-column>
          <a-table-column align="right" :width="44">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  status="danger"
                  size="mini"
                  @click="del(record)"
                >
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>

    <a-modal
      v-model:visible="formVisible"
      :title="(formItem ? '编辑' : '添加') + '课程'"
      :ok-loading="formLoading"
      :on-before-ok="formSubmit"
      width="800px"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules">
        <a-form-item field="course_ids" label="课程">
          <a-select v-model="formData.course_ids" multiple>
            <a-option
              v-for="item in courses"
              :value="item.id"
              :label="item.name"
            >
              <div class="option-course">
                <div class="img">
                  <img :src="item.image" />
                </div>
                <div class="content">
                  <div class="title">{{ item.name }}</div>
                  <div class="description">{{ item.description }}</div>
                </div>
              </div>
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="collection_id" label="板块">
          <div style="display: flex; width: 100%">
            <a-select
              style="flex: 1"
              v-model="formData.collection_id"
              allow-clear
              allow-search
            >
              <a-option v-for="item in collectionsOptions" :value="item.id">
                <div class="option-collection">
                  <div class="img">
                    <img :src="item.image" />
                  </div>
                  <div class="content">{{ item.name }}</div>
                </div>
              </a-option>
            </a-select>
            <a-button
              style="margin-left: 10px"
              type="primary"
              @click="collectionsRef.show(department)"
            >
              <template #icon>
                <icon-settings />
              </template>
              板块设置
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <collections ref="collectionsRef" @close="getCollections"></collections>
  </div>
</template>

<style lang="scss" scoped>
.page {
  height: 100%;
  display: flex;

  .aside {
    width: 200px;
    height: 100%;
    border-right: 1px solid #e5e6eb;
    background: #fff;
    overflow: auto;
    position: relative;

    .item {
      cursor: pointer;
      border-top: 1px solid #fff;
      border-bottom: 1px solid #fff;
      display: flex;
      align-items: center;
      height: 35px;
      padding-left: 10px;

      &:hover {
        background: #f6f8fb;
        color: #165dff;
      }

      &.active {
        color: #165dff;
        background: #f6f8fb;
        border-top: 1px solid #e5e6eb;
        border-bottom: 1px solid #e5e6eb;
      }

      &.active:first-child {
        border-top: 1px solid #f6f8fb;
      }
    }
  }

  .body {
    flex: 1;
    overflow: auto;
  }
}

.option-course {
  display: flex;
  padding: 5px;

  .img {
    width: 144px;
    height: 81px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    img {
      display: block;
      max-width: 100%;
      max-height: 100%;
    }
  }
  .content {
    padding-left: 5px;
    .title {
      line-height: 1;
    }

    .description {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.5);
      margin-top: 5px;
      line-height: 1.6;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      height: 36px;
      white-space: pre;
    }
  }
}

.cell-collection {
  display: flex;
  align-items: center;
  .img {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    margin-right: 5px;
    img {
      max-width: 100%;
      max-height: 100%;
      display: block;
    }
  }
}

.cell-course {
  display: flex;

  .img {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 144px;
    height: 81px;
    margin-right: 5px;
    img {
      max-width: 100%;
      max-height: 100%;
      display: block;
    }
  }

  .content {
    .description {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.5);
      margin-top: 5px;
      line-height: 1.6;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      height: 36px;
      white-space: pre;
    }
  }
}

.option-collection {
  display: flex;
  .img {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    margin-right: 5px;
    img {
      max-width: 100%;
      max-height: 100%;
      display: block;
    }
  }
}
</style>
